<template>
	<!-- 目前使用的VIP页面 -->
	<view class="flex-column" style="background-color: #f8f8f8; padding-bottom: 1rpx; box-sizing: border-box">
		<uni-nav-bar
			fixed="true"
			status-bar="true"
			left-icon=""
			left-width="60rpx"
			right-width="0"
			:border="false"
			background-color="#f8f8f8"
		>
			<view class="flex-row center-row" style="justify-content: center">
				<view class="flex-row center-row center-column swiperButton">
					<text class="swiperItem" @click="selItemIndex = 0">产品</text>
					<text class="swiperItem" @click="selItemIndex = 1">权益</text>
					<view class="view-item-line" :style="selItemIndex == 1 ? 'left: 56.5%' : ''"></view>
				</view>
			</view>
		</uni-nav-bar>
		<view v-show="selItemIndex == 0">
			<image
				class="vip_content_1"
				style="width: 100vw; height: 436rpx"
				src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_content_1.png"
				mode="aspectFit"
			></image>
			<view v-if="selVipIndex == 0" class="flex-column center-column center-row swiperItemContent">
				<text style="font-weight: 600; font-size: 48rpx; color: #3f4059">
					{{
						userInfo.isVIP > 0
							? userInfo.isVIP == 1
								? '您已经是志愿卡VIP会员'
								: userInfo.isVIP == 2
								? '您已经是升学卡VIP会员'
								: '您当前是志愿卡体验会员'
							: 'VIP会员限时优惠'
					}}
				</text>
				<text v-if="userInfo.isVIP > 0" style="font-size: 28rpx; color: #999999">
					会员到期日:{{ userInfo.expiretime }}
				</text>
			</view>
			<view v-else class="flex-column center-column center-row swiperItemContent">
				<text style="font-weight: 600; font-size: 48rpx; color: #3f4059">
					{{
						userInfo.isVIP == 2
							? '您已经是升学卡VIP会员'
							: userInfo.isVIP == 3
							? '您当前是志愿卡体验会员'
							: 'VIP会员限时优惠'
					}}
				</text>
				<text v-if="userInfo.isVIP == 2" style="font-size: 28rpx; color: #999999">
					会员到期日:{{ userInfo.expiretime }}
				</text>
			</view>
			<view class="flex-row chooseVip">
				<div class="image-container">
					<image
						:class="selVipIndex == 0 ? 'vip-image-sel' : 'vip-image-normal'"
						:src="'https://mcdn.chatgk.com/xcx/static/images/vip/vip_zyk_s.png'"
						@click="onClickVipItem(0)"
					></image>
					<div v-if="userInfo.isVIP != 1">
						<div class="money-icon">¥</div>
						<div class="money-pay">{{ storeInfo.vipprice }}</div>
					</div>
				</div>
				<div class="image-container">
					<image
						:class="selVipIndex == 1 ? 'vip-image-sel' : 'vip-image-normal'"
						style="margin-left: 44rpx"
						:src="'https://mcdn.chatgk.com/xcx/static/images/vip/vip_sxk_s.png'"
						@click="onClickVipItem(1)"
					></image>
					<div v-if="userInfo.isVIP != 2" style="margin-left: 44rpx">
						<div class="money-icon">¥</div>
						<div class="money-pay">{{ storeInfo.vipshengxueprice }}</div>
					</div>
				</div>
				<image
					class="vip-sel-icon"
					:style="selVipIndex == 1 ? 'left: 83%;' : ''"
					src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_item_sel.png"
				></image>
			</view>
			<view class="vip-button" @tap="onClickOpenVip">
				{{
					selVipIndex == 0
						? userInfo.isVIP > 0
							? '查看我的VIP会员权益'
							: '立即开通'
						: userInfo.isVIP == 2
						? '查看我的VIP会员权益'
						: '立即开通'
				}}
			</view>
			<image
				v-if="selVipIndex == 1"
				style="width: 100vw"
				src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_content_0.png"
				mode="aspectFit"
			></image>
			<image
				style="width: 100vw"
				src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_content_2.png"
				mode="aspectFit"
			></image>
			<image
				style="width: 100vw; margin-top: 40rpx"
				src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_content_3.png"
				mode="aspectFit"
			></image>
			<image
				style="width: 100vw; margin-top: 34rpx"
				src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_content_4.png"
				mode="aspectFit"
			></image>
			<image
				style="width: 100vw"
				src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_content_5.png"
				mode="aspectFit"
			></image>
			<view style="text-align: center; margin: 30rpx 0 200rpx 0; color: #ff1922" @click="navigatorTo">
				《会员服务协议》
			</view>
		</view>
		<view v-show="selItemIndex == 1">
			<image
				style="width: 100vw; height: 1318rpx"
				src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_equity.png"
				mode="aspectFit"
			></image>
		</view>
		<loading v-show="loadshow"></loading>
	</view>
</template>
<script>
import { Iap, IapTransactionState } from '/common/request/iap.js';
// import AppPay from '/common/request/appPay.js'
import userManager from '/common/manager/user-manager.js';
//    import md5 from 'js-md5'
//    const appPay = new AppPay()
export default {
	// onTabItemTap(e){
	// 	let {index,pagePath,text}=e
	// 	console.log(e);
	// 	console.log(index,pagePath,text,"======1");
	// 	if(uni.getStorageSync("is_visitor")==1&&[1,2].includes(index)){
	// 		uni.navigateTo({
	// 			url:"/pages/login/login-home"
	// 		})
	// 	}
	// 	return false
	// },
	data() {
		return {
			loadshow: false,
			currency_symbols: {
				CNY: '￥',
				RMB: '￥',
				USD: '$', // US Dollar
				EUR: '€', // Euro
				CRC: '₡', // Costa Rican Colón
				GBP: '£', // British Pound Sterling
				ILS: '₪', // Israeli New Sheqel
				INR: '₹', // Indian Rupee
				JPY: '¥', // Japanese Yen
				KRW: '₩', // South Korean Won
				NGN: '₦', // Nigerian Naira
				PHP: '₱', // Philippine Peso
				PLN: 'zł', // Polish Zloty
				PYG: '₲', // Paraguayan Guarani
				THB: '฿', // Thai Baht
				UAH: '₴', // Ukrainian Hryvnia
				VND: '₫' // Vietnamese Dong
			},
			productInfo: {
				price: '￥368'
			},
			iap: Iap,
			loading: false,
			productId: '',
			productList: [],
			userInfo: {},
			environment: '',
			selVipIndex: 0, // 0-志愿卡 1-升学卡
			selItemIndex: 0, // 0-产品 1-权益
			h5PlayData: {
				phone: '',
				card_type: '1',
				type: '1',
				redirectUrl: ''
			},
			storeInfo: JSON.parse(uni.getStorageSync('storeInfo')),
			vip_content_2_image: '',
			equipment: ''
		};
	},
	onLoad() {
		console.log(JSON.parse(uni.getStorageSync('storeInfo')), 'dddd');
		if (!this.userInfo.isVIP) {
			switch (uni.getSystemInfoSync().platform) {
				case 'android':
					console.log('运行Android上');
					this.environment = 'android';
					break;
				case 'ios':
					this.iap = new Iap({
						products: ['vip.volunteercard.388', 'vip.admissioncard.468'] // 苹果开发者中心创建
					});
					this.environment = 'ios';
					this.init();
					break;
				default:
					console.log('运行在开发者工具上');
					break;
			}
		}
		this.vip_content_2_image = this.storeInfo.logo;
		console.log('storeInfo', this.storeInfo.logo);
		// this.storeInfo = this.storeInfo
	},
	onShow() {
		this.userInfo = getApp().globalData.userInfo || {};
		this.equipment = uni.getSystemInfoSync('systemInfo').osName;
		uni.hideLoading();
	},
	methods: {
		navigatorTo() {
			uni.navigateTo({
				url: '/subpackages/subpackage1/pages/userAgreement/userAgreement'
			});
		},
		// 点击返回
		onClickBack() {
			uni.navigateBack();
		},
		// 点击绑定会员卡
		onClickBindingCard() {
			if (this.$userManager.isLogin()) {
				uni.navigateTo({
					url: '/pages/login/binding-card'
				});
			}
		},
		// 点击志愿卡or升学卡  0-志愿卡 1-升学卡
		onClickVipItem(index) {
			if (index == 0) {
				this.h5PlayData.card_type = '1';
			} else if (index == 1) {
				this.h5PlayData.card_type = '2';
			}
			this.selVipIndex = index;
		},
		async init() {
			// uni.showLoading({
			//     title: ''
			// })
			if (this.environment != 'ios') return;
			try {
				// 初始化，获取iap支付通道
				await this.iap.init();
				// 从苹果服务器获取产品列表
				this.productList = await this.iap.getProduct();
				console.log('------', this.productList);
				this.productList[0].checked = true;
				this.productId = this.productList[0].productid;
				this.productInfo = this.productList[0];
				const arr = this.productInfo.pricelocal.split('=') || [];
				let key = '';
				if (arr.length > 0) {
					key = arr[arr.length - 1];
				}
				key = this.currency_symbols[key] || '￥';
				this.productInfo['pricelocal'] = key;
			} catch (e) {
				uni.showModal({
					content: e.errMsg,
					showCancel: false
				});
			} finally {
				uni.hideLoading();
			}
			if (this.iap.ready) {
				// this.restore();
			}
		},
		async restore() {
			// 检查上次用户已支付且未关闭的订单，可能出现原因：首次绑卡，网络中断等异常
			// 在此处检查用户是否登陆
			// uni.showLoading({
			//     title: '正在检测已支付且未关闭的订单...'
			// });
			try {
				// 从苹果服务器检查未关闭的订单，可选根据 username 过滤，和调用支付时透传的值一致
				const transactions = await this.iap.restoreCompletedTransactions();
				if (!transactions.length) {
					return;
				}
				// 开发者业务逻辑，从服务器获取当前用户未完成的订单列表，和本地的比较
				// 此处省略
				switch (transaction.transactionState) {
					case IapTransactionState.purchased:
						// 用户已付款，在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
						//let result = await this.validatePaymentResult();
						// 验证通过，交易结束，关闭订单
						// if (result) {
						//   await this._iap.finishTransaction(transaction);
						// }
						break;
					case IapTransactionState.failed:
						// 关闭未支付的订单
						await this._iap.finishTransaction(transaction);
						break;
					default:
						break;
				}
			} catch (e) {
				uni.showModal({
					content: e.errMsg,
					showCancel: false
				});
			} finally {
				uni.hideLoading();
			}
		},
		// dialogInputConfirm(val) {
		//     this.h5PlayData.phone = val
		//     this.$request.h5Plau(this.h5PlayData).then(res => {
		//         location.href = res.data.h5_url
		//     })
		// },
		fetchCreatWeChatOrderAPI() {
			let reqObj = {
				openid: this.openid,
				transactions: 'xcx',
				serviceId: this.selVipIndex == 0 ? this.storeInfo.vipserviceid : this.storeInfo.vipshengxuserviceid
			};
			this.$request.creatWeChatOrderAPI(reqObj).then((res) => {
				if (res.code == 20000) {
					this.wxPlayData = res.data;
					wx.hideLoading();
					// 拿到参数调用微信支付接口
					wx.requestPayment({
						timeStamp: res.data.timeStamp + '',
						nonceStr: res.data.nonceStr,
						package: res.data.package,
						signType: 'MD5',
						paySign: res.data.paySign,
						success(res) {
							let visitor = uni.getStorageSync('visitorId') || {};
							if (visitor.visitorId) {
								visitor.buy = 1;
								this.$request.invitedNew(visitor).then((res) => {});
							}
							this.userInfo = getApp().globalData.userInfo;
							wx.showToast({
								title: '支付成功',
								icon: 'success',
								duration: 1000
							});
						},
						fail(res) {
							wx.showToast({
								title: '取消支付',
								icon: 'none',
								duration: 1000
							});
						}
					});
				}
			});
		},
		async onClickOpenVip() {
			let that = this;
			if (!this.$userManager.isLogin()) {
				uni.navigateTo({
					url: '/pages/login/login-home'
				});
				return;
			}
			const buttonText =
				this.selVipIndex == 0
					? this.userInfo.isVIP > 0
						? '查看我的VIP会员权益'
						: '立即开通'
					: this.userInfo.isVIP == 2
					? '查看我的VIP会员权益'
					: '立即开通';
			if (buttonText === '查看我的VIP会员权益') {
				this.selItemIndex = 1; // 设置 selItemIndex 为 1
				return;
			}
			// 微信小程序支付
			// #ifdef  MP-WEIXIN
			if (this.equipment == 'ios' || this.equipment == 'macos') {
				this.$request.sendPhoneH5().then((res) => {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				});
				return;
				// uni.showToast({
				//    title: '当前ios设备不支持',
				//    icon: 'none'
				// });
				// return;
			}
			wx.showLoading({
				title: '加载中...'
			});
			wx.login({
				success: (res) => {
					let userCode = res.code;
					// 将code传递给服务器
					this.$request
						.getWeChatAccessTokenXcx({
							code: userCode
						})
						.then((res) => {
							if (res.code == 20000) {
								this.openid = res.data.openid;
								this.fetchCreatWeChatOrderAPI();
							}
							// this.wxPlay = res.data
						});
				}
			});
			wx.hideLoading();
			// #endif
			// #ifdef APP-PLUS || H5
			if (this.environment == 'android') {
				// 发起微信支付
				appPay
					.wxPay()
					.then((resData) => {
						// let { res, orderInfo } = resData;
						// that.$request
						// 	.verifyWXPay({
						// 		out_trade_no: orderInfo
						// 	})
						// 	.then((res) => {
						// 		let visitor = uni.getStorageSync('visitorId') || {};
						// 		if (visitor.visitorId) {
						// 			visitor.buy = 1;
						// 			api.invitedNew(visitor).then((res) => {});
						// 			console.log(这里111111111);
						// 		}
						// 		this.userInfo = getApp().globalData.userInfo;
						// 	});
					})
					.catch((err) => {});
			} else {
				if (this.productInfo && Object.keys(this.productInfo).length > 0) {
					if (this.loading == true) {
						return;
					}
					this.loading = true;
					// 请求苹果支付
					// uni.showLoading({
					//     title: '购买中...',
					//     mask: true
					// })
					try {
						const transaction = await this.iap.requestPayment({
							productid: this.productInfo.productid
							// manualFinishTransaction: true,
						});
						// 支付成功
						// uni.showLoading({
						//     title: '',
						//     mask: true
						// })
						this.loadshow = false;
						// this.$request
						// 	.verify({
						// 		appid: '6446615912',
						// 		receipt: transaction.transactionReceipt,
						// 		consume: 1
						// 	})
						// 	.then((res) => {
						// 		this.loadshow = false;
						// 		uni.hideLoading();
						// 		uni.showToast({
						// 			title: '购买成功',
						// 			icon: 'success'
						// 		});
						// 		let visitor = uni.getStorageSync('visitorId') || {};
						// 		if (visitor.visitorId) {
						// 			visitor.buy = 1;
						// 			this.$request.invitedNew(visitor).then((res) => {});
						// 		}
						// 		this.userInfo = getApp().globalData.userInfo;
						// 	})
						// 	.catch((err) => {
						// 		uni.hideLoading();
						// 	});
					} catch (e) {
						uni.hideLoading();
						if (e.code != -100 && e.code != 2) {
							uni.showModal({
								content: e.errMsg,
								showCancel: false
							});
						}
					} finally {
						this.loading = false;
						uni.hideLoading();
					}
				} else {
					uni.showToast({
						title: '商品尚未准备好！',
						icon: 'none'
					});
				}
			}
			// #endif
		},
		generateNonceStr() {
			const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
			const len = chars.length;
			let nonceStr = '';
			for (let i = 0; i < 16; i++) {
				nonceStr += chars.charAt(Math.floor(Math.random() * len));
			}
			return nonceStr;
		}
	}
};
</script>
<style lang="scss">
.swiperButton {
	width: calc(100vw - 158rpx);
	color: #333333;
	font-size: 32rpx;
	text-align: center;
	display: flex;
	justify-content: center;
	.swiperItem {
		width: 120rpx;
		display: block;
		text-align: center;
	}
}
.swiperItemContent {
	margin-top: 22rpx;
	margin-bottom: 50rpx;
	display: flex;
	justify-content: center;
	flex-direction: column;
	align-items: center;
}
.chooseVip {
	position: relative;
	margin-bottom: 32rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}
.vip_content_1 {
	position: relative;
}
.vip_content_2 {
	width: 280rpx;
	height: 80rpx;
	position: absolute;
	top: 100rpx;
	left: 70rpx;
	background: #333333;
	z-index: 9999;
}
.text-nav-title {
	color: #333333;
	font-size: 16px;
	font-weight: 600;
	margin-left: 8rpx;
}
.text-nav-right {
	width: 140rpx;
	height: 50rpx;
	line-height: 50rpx;
	color: #ff3b0a;
	font-size: 11px;
	font-weight: 600;
	text-align: center;
	border: 2rpx solid #ff3b0a;
	border-radius: 30rpx;
}
.view-bottom-open {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	height: calc(env(safe-area-inset-bottom) + 112rpx + 40rpx);
	background-color: #fff;
	box-shadow: -6rpx 6rpx 14rpx rgba(0, 0, 0, 0.4);
}
.text-open-title {
	color: #fff;
	font-size: 28rpx;
	font-weight: bold;
}
.text-open-price {
	color: #fff;
	font-size: 48rpx;
	font-weight: bold;
}
.text-open-button {
	color: #fff;
	font-size: 36rpx;
	font-weight: bold;
	height: 100rpx;
	line-height: 100rpx;
}
.vip-button {
	position: fixed;
	bottom: 0;
	// bottom: 120rpx;
	z-index: 9999;
	width: 80vw;
	color: #fff;
	margin: 50rpx 82rpx 40rpx;
	font-size: 32rpx;
	font-weight: bold;
	text-align: center;
	border-radius: 46rpx;
	height: 92rpx;
	line-height: 92rpx;
	background: #ff3b0a;
	box-shadow: -6rpx 6rpx 10rpx rgba(0, 0, 0, 0.3);
}
.image-container {
	position: relative;
	display: inline-block;
	.vip-image-sel {
		width: 320rpx;
		height: 408rpx;
		border: 4rpx #ff3b0a solid;
		border-radius: 20rpx;
		box-shadow: 6rpx 6rpx 10rpx rgba(0, 0, 0, 0.25);
	}
	.vip-image-normal {
		width: 270rpx;
		height: 342rpx;
		border-radius: 20rpx;
		box-shadow: 6rpx 6rpx 10rpx rgba(0, 0, 0, 0.25);
	}
	.money-icon {
		margin: 0 45rpx;
		position: absolute;
		bottom: 20rpx;
		color: red;
		/* 文本颜色 */
		font-size: 12rpx;
		/* 文本大小 */
		padding: 10rpx;
		/* 内边距 */
	}
	.money-pay {
		margin: 0 55rpx;
		position: absolute;
		bottom: 15rpx;
		color: red;
		/* 文本颜色 */
		font-size: 24rpx;
		/* 文本大小 */
		padding: 10rpx;
		/* 内边距 */
	}
}
.vip-sel-icon {
	position: absolute;
	bottom: 25rpx;
	left: 41%;
	width: 44rpx;
	height: 44rpx;
}
.view-item-line {
	position: absolute;
	bottom: 15rpx;
	left: 40.5%;
	width: 24rpx;
	height: 4rpx;
	background-color: #ff3b0a;
}
</style>
